package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeListVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.events.Event;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private UserService userService;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //相互喜欢、喜欢和粉丝数据的统计查询。
    public Map counts() {
        Long userId = UserHolder.getUserId();
        Map count = userLikeApi.count(userId);
        return count;
    }

    public void fansLike(Long uid) {
        Long userId = UserHolder.getUserId();
        userLikeApi.fansLike(uid, userId);
    }

    public void deleteLike(Long uid) {
        Long userId = UserHolder.getUserId();
        userLikeApi.deleteLike(uid, userId);
    }


    public PageResult selectList(Integer type, Integer page, Integer pagesize, String nickname) {
        Long userId = UserHolder.getUserId();
        PageResult pageResult = new PageResult();
        pageResult.setPages(Long.valueOf(0));
        pageResult.setPage(page);
        pageResult.setCounts(Long.valueOf(0));
        pageResult.setPagesize(pagesize);
        /**
         * 1.互相喜欢
         * 2.我喜欢的
         * 3.粉丝-喜欢我的
         * 4.谁看过我
         */
        List<Long> userIds = new ArrayList<>();
        Boolean isLike  = false;
        switch (type) {
            case 1:
                PageResult eachLikePageResult = userLikeApi.queryEachLikeList(page, pagesize, userId);
                List<UserLike> items = (List<UserLike>) eachLikePageResult.getItems();
                List<Long> eachLikeUserIds = CollUtil.getFieldValues(items, "userId", Long.class);
                for (Long eachLikeUserId : eachLikeUserIds) {
                    userIds.add(eachLikeUserId);
                };
                break;
            case 2:
                PageResult LikePageResult = userLikeApi.queryLikeList(page, pagesize, userId);
                List<UserLike> items1 = (List<UserLike>) LikePageResult.getItems();
                List<Long> LikeUserIds = CollUtil.getFieldValues(items1, "likeUserId", Long.class);
                for (Long likeUserId : LikeUserIds) {
                    userIds.add(likeUserId);
                }
                break;
            case 3:
                PageResult fansPageResult = userLikeApi.queryfansList(page, pagesize, userId);
                List<UserLike> items2 = (List<UserLike>) fansPageResult.getItems();
                List<Long> fanUserIds = CollUtil.getFieldValues(items2, "userId", Long.class);
               /* for (UserLike userLike : items2) {
                    UserLike query = userLikeApi.query(userLike.getLikeUserId(), userLike.getUserId());
                    if(query!=null){
                        isLike = query.getIsLike();
                    }

                }*/
                for (Long fanUserId : fanUserIds) {
                    userIds.add(fanUserId);
                }
                break;
            case 4:
                PageResult visitorsPageResult = visitorsApi.queryVisitors(page, pagesize, userId);
                List<UserLike> items3 = (List<UserLike>) visitorsPageResult.getItems();
                List<Long> visitorUserIds = CollUtil.getFieldValues(items3, "visitorUserId", Long.class);
                for (Long visitorUserId : visitorUserIds) {
                    userIds.add(visitorUserId);
                }
                break;
            default: {
                break;
            }
        }
        if (CollUtil.isEmpty(userIds)) {
            return new PageResult();
        }
        List<UserInfo> userInfoList = userInfoApi.findList(userIds, nickname);
        List<UserLikeListVo> vos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            if (userInfo != null) {
                UserLikeListVo vo = new UserLikeListVo();
                BeanUtils.copyProperties(userInfo, vo);
                RecommendUser recommendUser = recommendUserApi.queryByUserId(userId, userInfo.getId());
                Double score = recommendUser.getScore();
                if (score == null) {
                    RandomUtil.randomDouble(30, 90);
                }
                vo.setMatchRate(Integer.valueOf(score.intValue()));
                if (type == 3){
                    UserLike query = userLikeApi.query(UserHolder.getUserId(),userInfo.getId() );
                    if(query==null){
                        vo.setAlreadyLove(isLike);
                    }else {
                        vo.setAlreadyLove(query.getIsLike());
                    }

                }
                vos.add(vo);
            }
        }
        pageResult.setItems(vos);
        return pageResult;
    }


    /**
     * 更换手机号 发送验证码
     */

    public void sendVerificationCode(String token) {

        long userId = UserHolder.getUserId();
        User user = userApi.findById(userId);

        String phone = user.getMobile();
        userService.sendMsg(phone);

    }


    /**
     * 更换手机号 校验验证码
     *
     * @return
     */
    public Map checkVerificationCode(String verificationCode) {

        long userId = UserHolder.getUserId();
        User user = userApi.findById(userId);
        String phone = user.getMobile();
        //①从Redis获 取验证码
        String redisCode = (String) redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        //②判断验证码是否合法(验证码是否存在，是否一致)
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(verificationCode)) {
            // 验证码失效或者错误   抛出一个异常
            throw new BusinessException(ErrorResult.loginError());

        }
        //删除redis 中的验证码
        Boolean delete = redisTemplate.delete("CHECK_CODE_" + phone);
        //⑥构造数据响应
        Map map = new HashMap();
        map.put("verification", delete);
        return map;

    }

    /**
     * 更换手机号 存新手机号
     *
     * @param phone
     */
    public void savenewphone(String phone) {

        //③根据手机号码查询用户
        User user = userApi.findByMobile(phone);
        //④判断用户是否存在，若不存在添加新用户

        if (user == null) {
            long userId1 = UserHolder.getUserId();
            User user1 = userApi.findById(userId1);
            user1.setMobile(phone);
            // 调用存进数据库
            userApi.updatePhone(user1);
        }else {
            throw new BusinessException(ErrorResult.mobileError());
        }

    }
}
